package com.group3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group3.dao.LiveMessageMapper;
import com.group3.dao.LiveProductMapper;
import com.group3.dao.LiveRoomMapper;
import com.group3.entity.LiveMessage;
import com.group3.entity.LiveProduct;
import com.group3.entity.LiveRoom;
import com.group3.service.LiveRoomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

    @Resource
    private LiveProductMapper liveProductMapper;

    @Resource
    private LiveMessageMapper liveMessageMapper;

    @Override
    @Transactional
    public LiveRoom createLiveRoom(LiveRoom liveRoom) {
        liveRoom.setStatus(0); // 未开始
        liveRoom.setViewerCount(0);
        liveRoom.setLikeCount(0);
        liveRoom.setGiftCount(0);
        save(liveRoom);

        // 保存关联商品
        if (liveRoom.getProductIds() != null && !liveRoom.getProductIds().isEmpty()) {
            for (int i = 0; i < liveRoom.getProductIds().size(); i++) {
                LiveProduct lp = new LiveProduct();
                lp.setLiveId(liveRoom.getId());
                lp.setProductId(liveRoom.getProductIds().get(i));
                lp.setSort(i);
                liveProductMapper.insert(lp);
            }
        }

        return liveRoom;
    }

    @Override
    @Transactional
    public LiveRoom updateLiveRoom(LiveRoom liveRoom) {
        updateById(liveRoom);

        // 先删除原有商品关联
        QueryWrapper<LiveProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("live_id", liveRoom.getId());
        liveProductMapper.delete(wrapper);

        // 再添加新的商品关联
        if (liveRoom.getProductIds() != null && !liveRoom.getProductIds().isEmpty()) {
            for (int i = 0; i < liveRoom.getProductIds().size(); i++) {
                LiveProduct lp = new LiveProduct();
                lp.setLiveId(liveRoom.getId());
                lp.setProductId(liveRoom.getProductIds().get(i));
                lp.setSort(i);
                liveProductMapper.insert(lp);
            }
        }

        return liveRoom;
    }

    @Override
    @Transactional
    public void deleteLiveRoom(Long id) {
        // 删除直播间
        removeById(id);

        // 删除关联商品
        QueryWrapper<LiveProduct> productWrapper = new QueryWrapper<>();
        productWrapper.eq("live_id", id);
        liveProductMapper.delete(productWrapper);

        // 删除关联消息
        QueryWrapper<LiveMessage> messageWrapper = new QueryWrapper<>();
        messageWrapper.eq("live_id", id);
        liveMessageMapper.delete(messageWrapper);
    }

    @Override
    public LiveRoom getLiveRoomById(Long id) {
        return getById(id);
    }

    @Override
    public Page<LiveRoom> listLiveRooms(int page, int size) {
        return page(new Page<>(page, size));
    }

    @Override
    public List<LiveRoom> getRecommendedRooms(Long userId, int limit) {
        return baseMapper.findRecommendedRooms(userId, limit);
    }

    @Override
    public void startLive(Long liveId) {
        LiveRoom liveRoom = getById(liveId);
        if (liveRoom != null) {
            liveRoom.setStatus(1); // 直播中
            liveRoom.setStartTime(LocalDateTime.now());
            updateById(liveRoom);
        }
    }

    @Override
    public void pauseLive(Long liveId) {
        LiveRoom liveRoom = getById(liveId);
        if (liveRoom != null) {
            liveRoom.setStatus(3); // 暂停
            updateById(liveRoom);
        }
    }

    @Override
    public void endLive(Long liveId) {
        LiveRoom liveRoom = getById(liveId);
        if (liveRoom != null) {
            liveRoom.setStatus(2); // 已结束
            liveRoom.setEndTime(LocalDateTime.now());
            updateById(liveRoom);
        }
    }

    @Override
    public void addProductToLive(Long liveId, Long productId) {
        LiveProduct lp = new LiveProduct();
        lp.setLiveId(liveId);
        lp.setProductId(productId);

        // 获取当前最大sort值
        QueryWrapper<LiveProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("live_id", liveId);
        wrapper.orderByDesc("sort");
        wrapper.last("limit 1");
        LiveProduct last = liveProductMapper.selectOne(wrapper);

        lp.setSort(last != null ? last.getSort() + 1 : 0);
        liveProductMapper.insert(lp);
    }

    @Override
    public void removeProductFromLive(Long liveId, Long productId) {
        QueryWrapper<LiveProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("live_id", liveId);
        wrapper.eq("product_id", productId);
        liveProductMapper.delete(wrapper);
    }

    @Override
    public List<LiveMessage> getLiveMessages(Long liveId, int limit) {
        QueryWrapper<LiveMessage> wrapper = new QueryWrapper<>();
        wrapper.eq("live_id", liveId);
        wrapper.orderByDesc("create_time");
        wrapper.last("limit " + limit);
        return liveMessageMapper.selectList(wrapper);
    }

    @Override
    public void sendMessage(LiveMessage message) {
        message.setCreateTime(LocalDateTime.now());
        liveMessageMapper.insert(message);

        // 如果是点赞或礼物，更新直播间计数
        if (message.getType() == 1) { // 点赞
            LiveRoom liveRoom = getById(message.getLiveId());
            if (liveRoom != null) {
                liveRoom.setLikeCount(liveRoom.getLikeCount() + 1);
                updateById(liveRoom);
            }
        } else if (message.getType() == 2) { // 礼物
            LiveRoom liveRoom = getById(message.getLiveId());
            if (liveRoom != null) {
                liveRoom.setGiftCount(liveRoom.getGiftCount() + 1);
                updateById(liveRoom);
            }
        }
    }
}
